﻿using Castle.DynamicProxy;
using Microsoft.Extensions.Caching.Memory;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Common.Extensions
{
    public class MemoryCaching : ICaching
    {
        private IMemoryCache _cache;

        public MemoryCaching(IMemoryCache cache)
        {
            _cache = cache;
        }

        public bool DelCache(string cacheKey)
        {
            if (string.IsNullOrEmpty(cacheKey)) return false;
            else _cache.Remove(cacheKey); return !Exists(cacheKey);
        }

        public bool Exists(string cacheKey)
        {
            object value;
            if (string.IsNullOrEmpty(cacheKey)) return false;
            return _cache.TryGetValue(cacheKey, out value);
        }

        public object GetCache(string cahcheKey)
        {
            return _cache.Get(cahcheKey);
        }

        public void SetCache(string cacheKey, object cacheValue, MemoryCacheEntryOptions options)
        {
            _cache.Set(cacheKey, cacheValue, options);
        }

        public string SetCacheKey(IInvocation invocation)
        {
            var key = $"{DateTime.Now.ToString("yyyyMMdd")}{invocation.TargetType.Name}{invocation.Method.Name}";
            return key;
        }
    }
}
